package b1.mobile.blackberry.dao;

import java.util.Vector;

import net.rim.device.api.io.MalformedURIException;
import net.rim.device.api.io.URI;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;

import b1.mobile.blackberry.controller.AgentController;
import b1.mobile.blackberry.entity.ReportEntity;
import b1.mobile.blackberry.io.http.ResponseParserHelper;
import b1.mobile.blackberry.io.http.Serviceworker;
import b1.mobile.blackberry.io.http.SoapContentProvider;
import b1.mobile.blackberry.ui.component.util.Capsule;

public class ReportDAO extends CommonDAO {
	public static String OP_LIST = "GetReportTypeList";
	public static String OP_GET = "GetReportByCode";
	
	public ReportDAO(DataAccessDelegate delegate){
		super(delegate);
	}

	public void onGetResult(Serviceworker worker) {
		if(worker.responseCode == 200){
			if(worker.getOperator().equals(OP_LIST)){
				parseList(worker);
			} else if(worker.getOperator().equals(OP_GET)){
				parse(worker);
			}
		}
	}
	
	public void list(){
		String[] names = new String[]{};
		String[] values = new String[]{};
		SoapContentProvider soap = new SoapContentProvider(OP_LIST, names, values);
		
		try {
			Serviceworker _worker = new Serviceworker(this, AgentController.getServer(), soap);
			new Thread(_worker).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void parseList(Serviceworker worker){
		ResponseParserHelper help = new ResponseParserHelper(worker.responseMessage);
		JSONArray array = (JSONArray)help.parse("GetReportTypeListResult");
		
		Vector items = new Vector();
		for(int i = 0; i < array.length(); i++){
			try {
				JSONObject json = array.getJSONObject(i);
				ReportEntity ety = new ReportEntity(json);
				items.addElement(new Capsule(ety.getCode(), ety));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}	
		_delegate.onDataReady(worker, items);
	}
	
	public void get(String code){
		String[] names = new String[]{"Code"};
		String[] values = new String[]{code};
		SoapContentProvider soap = new SoapContentProvider(OP_GET, names, values);
		
		try {
			Serviceworker _worker = new Serviceworker(this, AgentController.getServer(), soap);
			new Thread(_worker).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void parse(Serviceworker worker){
		ResponseParserHelper help = new ResponseParserHelper(worker.responseMessage);
		String tempUrlStr = (String)help.parse("GetReportByCodeResult");
		String realUrlStr = tempUrlStr;
		try {
			realUrlStr = AgentController.getServer().getServerUrl() + URI.create(tempUrlStr).getPath();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURIException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		_delegate.onDataReady(worker, realUrlStr);
	}
}
